Index
Guide Example and Challenge


In this chapter we code js classes from end-to-end.

It's all driven by a "guide example".

When you are ready:


Static Variables


Static variables (class variables) are variables that are associated with the given class and not an object instance like ivars.

Js does not have formal support for static variables (side note: as of 2021 there is work to add support).

However, even without formal support, because of JavaScript's general flexibility we are able to code them. And it is simple.

First Let Us Look At 'this'
The keyword this used inside a static method refers to the class (not an object instance).
class Play {
	static meStaticMethod() {
		prn(this===Play);
		//prints true
	}
}
Coding a Static Variable
Here we see how to code a static variable named "Foo" with static getter "getFoo".

We use the nullish coalescing operator. The logical OR operator is another option but not as reliable (play with "0 || 10" in a lab).
class Play {
	static getFoo() {
		return this.Foo ?? (this.Foo = 'Me Static!!');
	}
}

console.log(Play.getFoo());
//prints 'Me Static!!'
Or Like This
Using an old-fashioned if statement
class Play {
	static getFoo() {
		if (!this.Foo)
			this.Foo = 'Me Static';
		return this.Foo;
	}
}

console.log(Play.getFoo());
//prints 'Me Static'